<?php

namespace app\admin\controller\cms;
use app\admin\controller\Base;
use think\facade\Request;
use think\facade\View;
use app\admin\model\cms\Category;

class Article extends Base
{
    protected $categorys,$treedata;
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\cms\Article;
        $this->redict = url('index');
        $categorys = Category::field('id,pid,title,catdir')->select()->toArray();

        $categorys = cateTree($categorys);

        foreach ($categorys as $key => $value) {
            $this->categorys[$value['id']] = $value;
        }
        $this->treedata = tree($this->categorys);

        View::assign('treedata',json_encode($this->treedata));
        View::assign('categorys',$this->categorys);
    }
    public function index(){
        if (Request::isPost()) {
            $title = $this->request->post('title', '', 'trim');
            $catids = $this->request->post('catids');
            $where[] = ['title','like','%'.$title.'%'];
            if ($catids) {
                $where[] = ['catid','in',$catids];
            }
            $option = [
                'where' => $where,
                'with' => ['cate'],  // 关联的模型名称
                'visible' => [
                    'cate' => ['title']  // 关联的模型名称要显示的字段名，默认展示全部
                ]
            ];
            $list = $this->model->loadList($option);
            if ($list['result'] == 'success'){
                $result = ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['list'], 'count' => $list['page']['total']];
            }else{
                $result = ['code' => 0, 'msg' => $list['msg'], 'data' => [], 'count' => 0];
            }
            return $result;
        }
        return view();
    }
    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function add()
    {
        if (Request::isPost()) {
            return parent::create();
        }else{
            return parent::add();
        }

    }
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function edit()
    {
        if (Request::isPost()) {
            return parent::modify();
        }else{
            return parent::read('add');
        }
    }

}